package top.lgd.service;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import top.lgd.base.LgdConstants;

import java.util.concurrent.TimeUnit;

import static top.lgd.base.LgdConstants.FOUR;

/**
 * @author YYJ
 * @version 1.0
 * @since 2023/12/15 14:12
 */
@Slf4j
@Service
public class LgdCacheService {

    // 创建缓存实例
    private Cache<String, Object> lgdCache = CacheBuilder.newBuilder().maximumSize(LgdConstants.LGD_CACHES).expireAfterWrite(FOUR, TimeUnit.DAYS).build();

    /**
     * 获取缓存
     *
     * @param key
     * @param <T>
     * @return
     */
    public <T> T get(String key) {
        long start = System.currentTimeMillis();
        Object data = null;
        try {
            data = lgdCache.getIfPresent(key);
        } catch (Exception e) {
            log.error("> 查询缓存[{}]失败", key, e);
        } finally {
            log.info("> 查询缓存[{}] 结果[{}]耗时:{}ms", key, (null == data ? "无" : "有"), (System.currentTimeMillis() - start));
        }
        return (T) data;
    }

    /**
     * 获取缓存并再缓存
     *
     * @param key
     * @param <T>
     * @return
     */
    public <T> T getAndRenew(String key) {
        T data = get(key);
        if (null != data) {
            put(key, data);
        }
        return data;
    }

    public void put(String key, Object value) {
        try {
            lgdCache.put(key, value);
        } catch (Exception e) {
            log.error("> 保存缓存[{}]失败", key, e);
        }
    }

    public void delete(String key) {
        try {
            lgdCache.invalidate(key);
        } catch (Exception e) {
            log.error("> 清理缓存[{}]失败", key, e);
        }
    }
}